package com.waikuai.shop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.entity.ProductReview;
import com.waikuai.shop.service.ProductReviewService;
import com.waikuai.shop.service.UserService;
import com.waikuai.shop.vo.ProductReviewVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 商品评价控制器
 * @author waikuai
 */
@Slf4j
@RestController
@RequestMapping("/reviews")
@RequiredArgsConstructor
@Validated
public class ProductReviewController {

    private final ProductReviewService productReviewService;
    private final UserService userService;

    /**
     * 分页查询商品评价列表
     */
    @GetMapping
    public Result<IPage<ProductReviewVO>> getReviewPage(
            @RequestParam Long productId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status) {
        try {
            Page<ProductReview> page = new Page<>(current, size);
            IPage<ProductReviewVO> result = productReviewService.getReviewPage(page, productId, status);
            
            log.info("分页查询商品评价列表成功，商品ID: {}, 页码: {}, 页大小: {}, 总数: {}", 
                    productId, current, size, result.getTotal());
            return Result.success("查询评价列表成功", result);
        } catch (Exception e) {
            log.error("分页查询商品评价列表失败，商品ID: {}", productId, e);
            return Result.error("查询评价列表失败");
        }
    }

    /**
     * 获取商品评价列表（不分页）
     */
    @GetMapping("/product/{productId}")
    public Result<List<ProductReviewVO>> getReviewsByProductId(
            @PathVariable Long productId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductReviewVO> reviews = productReviewService.getReviewsByProductId(productId, status, limit);
            
            log.info("获取商品评价列表成功，商品ID: {}, 数量: {}", productId, reviews.size());
            return Result.success("查询评价列表成功", reviews);
        } catch (Exception e) {
            log.error("获取商品评价列表失败，商品ID: {}", productId, e);
            return Result.error("查询评价列表失败");
        }
    }

    /**
     * 添加商品评价
     */
    @PostMapping
    public Result<String> addReview(@RequestBody Map<String, Object> request) {
        try {
            Long userId = getCurrentUserId();
            Long productId = getLongValue(request.get("productId"));
            Integer rating = getIntegerValue(request.get("rating"));
            String content = (String) request.get("content");
            @SuppressWarnings("unchecked")
            List<String> images = (List<String>) request.get("images");

            if (productId == null) {
                return Result.error("商品ID不能为空");
            }
            if (rating == null || rating < 1 || rating > 5) {
                return Result.error("评分必须在1-5之间");
            }

            boolean result = productReviewService.addReview(userId, productId, rating, content, images);
            
            if (result) {
                log.info("添加商品评价成功，用户ID: {}, 商品ID: {}, 评分: {}", userId, productId, rating);
                return Result.success("评价提交成功");
            } else {
                return Result.error("评价提交失败");
            }
        } catch (Exception e) {
            log.error("添加商品评价失败: {}", e.getMessage(), e);
            return Result.error("评价提交失败");
        }
    }

    /**
     * 统计商品评价数量
     */
    @GetMapping("/count/{productId}")
    public Result<Integer> countReviews(@PathVariable Long productId,
                                       @RequestParam(required = false) Integer status) {
        try {
            Integer count = productReviewService.countReviewsByProductId(productId, status);
            
            log.info("统计商品评价数量成功，商品ID: {}, 数量: {}", productId, count);
            return Result.success("查询成功", count);
        } catch (Exception e) {
            log.error("统计商品评价数量失败，商品ID: {}", productId, e);
            return Result.error("查询失败");
        }
    }

    /**
     * 计算商品平均评分
     */
    @GetMapping("/rating/{productId}")
    public Result<Double> getAverageRating(@PathVariable Long productId,
                                          @RequestParam(required = false) Integer status) {
        try {
            Double avgRating = productReviewService.calculateAverageRating(productId, status);
            
            log.info("计算商品平均评分成功，商品ID: {}, 平均评分: {}", productId, avgRating);
            return Result.success("查询成功", avgRating);
        } catch (Exception e) {
            log.error("计算商品平均评分失败，商品ID: {}", productId, e);
            return Result.error("查询失败");
        }
    }

    /**
     * 审核评价（管理员接口）
     */
    @PutMapping("/{reviewId}/audit")
    public Result<String> auditReview(@PathVariable Long reviewId,
                                     @RequestParam Integer status) {
        try {
            boolean result = productReviewService.auditReview(reviewId, status);
            
            if (result) {
                log.info("审核评价成功，评价ID: {}, 状态: {}", reviewId, status);
                return Result.success("审核成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            log.error("审核评价失败，评价ID: {}", reviewId, e);
            return Result.error("审核失败");
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            throw new RuntimeException("用户未登录");
        }
        
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            String username = userDetails.getUsername();
            
            com.waikuai.shop.entity.User user = userService.findByUsername(username);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            return user.getId();
        } else {
            throw new RuntimeException("无法获取用户信息");
        }
    }

    /**
     * 从Object获取Long值
     */
    private Long getLongValue(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.parseLong(value.toString());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从Object获取Integer值
     */
    private Integer getIntegerValue(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (Exception e) {
            return null;
        }
    }
}

